<template>
  <view class="push-setting-page">
    <!-- 页面标题 -->
    <!-- 策略列表 -->
    <view class="strategy-list" v-if="strategyList.length > 0">
      <view 
        class="strategy-card" 
        v-for="(strategy, index) in strategyList" 
        :key="strategy.strategyId"
      >
        <!-- 策略头部：名称和开关 -->  
        <view class="strategy-header">
          <view class="strategy-info">
            <text class="strategy-name">{{ strategy.strategyName }}</text>
            <text class="strategy-desc">高胜率高复利</text>
          </view>
          <view class="strategy-switch">
            <uv-switch
              v-model="strategy.pushEnabled"
              :active-color="themeColor"
              :inactive-color="inactiveColor"
              @change="(val) => onPushChange(strategy, val)"
            ></uv-switch>
          </view>
        </view>

        <!-- 周期推送设置 - 只有开启推送时才显示 -->
        <view 
          class="period-setting" 
          v-if="strategy.pushEnabled"
          @click="openPeriodPopup(strategy)"
        >
          <view class="period-left">
            <text class="period-title">周期推送设置</text>
            <text class="period-desc" v-if="strategy.periods && strategy.periods.length > 0">
              已选择 {{ strategy.periods.length }} 个周期
            </text>
            <text class="period-desc empty" v-else>未选择周期</text>
          </view>
          <view class="period-right">
            <uv-icon name="arrow-right" color="#999" size="16"></uv-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <text class="empty-text">暂无策略配置</text>
    </view>

    <!-- 周期推送设置弹窗 -->
    <uv-popup 
      ref="periodPopup" 
      mode="bottom" 
      :round="20" 
      :close-on-click-overlay="true"
      :safe-area-inset-bottom="true"
    >
      <view class="period-popup">
        <!-- 弹窗标题栏 -->
        <view class="popup-header">
          <text class="popup-title">周期推送设置</text>
          <view class="close-btn" @click="closePeriodPopup">
            <uv-icon name="close" size="20" color="#999"></uv-icon>
          </view>
        </view>

        <!-- 温馨提醒 -->
        <view class="warm-tips">
          <text class="tips-text">温馨提醒：本策略时间周期默认配置是胜率最高的配置，不建议进行配置更改，消息面会干扰量化信号的大周期，所以遇到消息面，可以打开5分钟来临时应变。</text>
        </view>

        <!-- 周期选项（多选，3列布局） -->
        <view class="period-grid">
          <view 
            v-for="period in allPeriods" 
            :key="period.id" 
            class="period-checkbox-item"
            @click="togglePeriod(period)"
          >
            <view class="checkbox-icon" :class="{ checked: isPeriodSelected(period) }">
              <uv-icon v-if="isPeriodSelected(period)" name="checkbox-mark" color="#fff" size="18"></uv-icon>
            </view>
            <text class="period-label">{{ period.cycleName }}</text>
          </view>
        </view>

        <!-- 保存按钮 -->
        <view class="save-button" @click="savePeriodSettings">
          <text class="save-button-text">保存</text>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import {
  getStrategyType,
  getUserStrategyPushSetting,
  getPeriods,
  setStrategyPush,
  cancelStrategyPush
} from '@/api/tactics'

export default {
  data() {
    return {
      themeColor: '#06CBB6',
      inactiveColor: '#E5E5E5',
      loading: false,
      
      // 策略列表
      strategyList: [],
      
      // 用户已配置的推送设置
      userPushSettings: [],
      
      // 所有可选周期
      allPeriods: [],
      
      // 当前编辑的策略
      currentStrategy: null,
      
      // 临时选中的周期
      tempSelectedPeriods: []
    }
  },

  onLoad() {
    this.init()
  },

  methods: {
    /**
     * 初始化数据
     */
    async init() {
      try {
        this.loading = true
        uni.showLoading({ title: '加载中...', mask: true })

        // 并行获取数据
        await Promise.all([
          this.getStrategyList(),
          this.getUserPushSettings()
        ])

        // 回显用户已配置的推送设置
        this.mergeUserSettings()

        uni.hideLoading()
        this.loading = false
      } catch (error) {
        console.error('初始化失败:', error)
        uni.hideLoading()
        this.loading = false
        uni.showToast({
          title: error.message || '加载失败',
          icon: 'none'
        })
      }
    },

    /**
     * 获取策略列表（作为默认列表）
     */
    async getStrategyList() {
      const res = await getStrategyType()
      console.log('策略列表:', res)
      
      if (res.code === 200 && res.data && res.data.length > 0) {
        // 提取所有策略
        const allStrategies = []
        res.data.forEach(category => {
          if (category.strategies && category.strategies.length > 0) {
            category.strategies.forEach(strategy => {
              allStrategies.push({
                strategyId: strategy.id,
                strategyName: strategy.strategyName,
                description: strategy.description || '高胜率高复利',
                pushEnabled: false,
                periods: []
              })
            })
          }
        })
        this.strategyList = allStrategies
        console.log('处理后的策略列表:', this.strategyList)
      }
    },

    /**
     * 获取用户已配置的推送设置
     */
    async getUserPushSettings() {
      try {
        const res = await getUserStrategyPushSetting()
        console.log('用户推送配置:', res)
        
        if (res.code === 200 && res.data) {
          this.userPushSettings = res.data
        }
      } catch (error) {
        console.error('获取用户推送配置失败:', error)
        // 不影响主流程，继续显示默认列表
      }
    },

    /**
     * 合并用户设置到策略列表
     */
    mergeUserSettings() {
      if (!this.userPushSettings || this.userPushSettings.length === 0) {
        return
      }

      // 遍历策略列表，回显用户配置
      this.strategyList.forEach(strategy => {
        const userSetting = this.userPushSettings.find(
          s => s.strategyId === strategy.strategyId
        )
        
        if (userSetting) {
          // 回显已配置的数据
          strategy.pushEnabled = userSetting.periods && userSetting.periods.length > 0
          strategy.periods = userSetting.periods || []
          strategy.currencies = userSetting.currencies || []
        }
      })

      console.log('合并后的策略列表:', this.strategyList)
    },

    /**
     * 获取周期列表（根据策略ID）
     */
    async getAllPeriods(strategyId) {
      try {
        const res = await getPeriods({ strategyId: strategyId })
        if (res.code === 200 && res.data && res.data.records) {
          this.allPeriods = res.data.records
          console.log('周期列表:', this.allPeriods)
        }
      } catch (error) {
        console.error('获取周期列表失败:', error)
      }
    },

    /**
     * 推送开关变更
     */
    async onPushChange(strategy, value) {
      console.log('推送开关变更:', strategy.strategyName, value)

      if (!value) {
        // 关闭推送
        try {
          uni.showLoading({ title: '处理中...', mask: true })

          const res = await cancelStrategyPush({
            strategyId: strategy.strategyId
          })

          uni.hideLoading()

          if (res.code === 200) {
            strategy.pushEnabled = false
            strategy.periods = []
            uni.showToast({ title: '已关闭推送', icon: 'none' })
          } else {
            throw new Error(res.message || '关闭推送失败')
          }
        } catch (error) {
          console.error('关闭推送失败:', error)
          strategy.pushEnabled = true // 恢复开关状态
          uni.hideLoading()
          uni.showToast({
            title: error.message || '操作失败',
            icon: 'none'
          })
        }
      } else {
        // 开启推送时提示用户选择周期
        uni.showToast({
          title: '请点击"周期推送设置"选择周期',
          icon: 'none'
        })
      }
    },

    /**
     * 打开周期选择弹窗
     */
    async openPeriodPopup(strategy) {
      this.currentStrategy = strategy
      
      // 先获取该策略的周期列表
      uni.showLoading({ title: '加载中...', mask: true })
      await this.getAllPeriods(strategy.strategyId)
      uni.hideLoading()
      
      // 初始化临时选中的周期
      if (strategy.periods && strategy.periods.length > 0) {
        // 根据 periodId 匹配 allPeriods 中的完整数据
        this.tempSelectedPeriods = strategy.periods.map(p => {
          const found = this.allPeriods.find(ap => ap.id === p.periodId)
          return found || { id: p.periodId, cycleName: p.periodName }
        })
      } else {
        this.tempSelectedPeriods = []
      }
      
      this.$refs.periodPopup.open()
    },

    /**
     * 关闭周期选择弹窗
     */
    closePeriodPopup() {
      this.$refs.periodPopup.close()
      this.currentStrategy = null
      this.tempSelectedPeriods = []
    },

    /**
     * 判断周期是否已选中
     */
    isPeriodSelected(period) {
      return this.tempSelectedPeriods.some(p => p.id === period.id)
    },

    /**
     * 切换周期选择状态
     */
    togglePeriod(period) {
      const index = this.tempSelectedPeriods.findIndex(p => p.id === period.id)
      
      if (index > -1) {
        this.tempSelectedPeriods.splice(index, 1)
      } else {
        this.tempSelectedPeriods.push(period)
      }
    },

    /**
     * 保存周期设置
     */
    async savePeriodSettings() {
      if (!this.currentStrategy) return

      // 验证是否已选择周期
      if (this.tempSelectedPeriods.length === 0) {
        uni.showToast({
          title: '请至少选择一个周期',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({ title: '保存中...', mask: true })

        const periodIds = this.tempSelectedPeriods.map(p => Number(p.id))

        const params = {
          strategyId: Number(this.currentStrategy.strategyId),
          periodIds: periodIds
        }

        console.log('保存推送设置参数:', params)

        const res = await setStrategyPush(params)

        uni.hideLoading()

        if (res.code === 200) {
          // 更新当前策略的周期数据
          this.currentStrategy.periods = this.tempSelectedPeriods.map(p => ({
            periodId: p.id,
            periodName: p.cycleName
          }))
          this.currentStrategy.pushEnabled = true

          this.closePeriodPopup()
          
          uni.showToast({
            title: '保存成功',
            icon: 'none'
          })
        } else {
          throw new Error(res.message || '保存失败')
        }
      } catch (error) {
        console.error('保存设置失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.push-setting-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #E8F8F6 0%, #f5f5f5 30%);
  padding: 32rpx;
}

/* 页面标题 */
.page-header {
  padding: 20rpx 0 40rpx;
  text-align: center;

  .page-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

/* 策略列表 */
.strategy-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

/* 策略卡片 */
.strategy-card {
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

/* 策略头部 */
.strategy-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;

  .strategy-info {
    flex: 1;
    margin-right: 24rpx;

    .strategy-name {
      display: block;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
    }

    .strategy-desc {
      display: block;
      font-size: 24rpx;
      color: #999;
    }
  }

  .strategy-switch {
    flex-shrink: 0;
  }
}

/* 周期推送设置 */
.period-setting {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  margin: 0 24rpx 24rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    opacity: 0.8;
  }

  .period-left {
    flex: 1;

    .period-title {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 6rpx;
    }

    .period-desc {
      display: block;
      font-size: 24rpx;
      color: #06CBB6;
      font-weight: 500;

      &.empty {
        color: #999;
        font-weight: 400;
      }
    }
  }

  .period-right {
    flex-shrink: 0;
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 周期选择弹窗 */
.period-popup {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  padding: 0 40rpx 40rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 0 32rpx;
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 10;

  .popup-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }

  .close-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48rpx;
    height: 48rpx;
    cursor: pointer;

    &:active {
      opacity: 0.6;
    }
  }
}

/* 温馨提醒 */
.warm-tips {
  padding: 24rpx;
  margin-bottom: 32rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  border-left: 6rpx solid #06CBB6;

  .tips-text {
    font-size: 24rpx;
    line-height: 1.8;
    color: #666;
  }
}

/* 周期选项网格 */
.period-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12rpx;
  margin-bottom: 48rpx;
}

.period-checkbox-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 16rpx 12rpx;
  background: transparent;
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    opacity: 0.7;
  }

  .checkbox-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40rpx;
    height: 40rpx;
    background: #fff;
    border: 3rpx solid #ddd;
    border-radius: 8rpx;
    flex-shrink: 0;
    transition: all 0.3s ease;

    &.checked {
      background: #06CBB6;
      border-color: #06CBB6;
    }
  }

  .period-label {
    font-size: 26rpx;
    color: #333;
    font-weight: 400;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 保存按钮 */
.save-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  background: linear-gradient(135deg, #06cbb6 0%, #04a89e 100%);
  border-radius: 16rpx;
  margin-top: 32rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }

  .save-button-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #fff;
  }
}
</style>
